<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">申请人</label>
        <el-select
          v-model="query.userId"
          clearable
          style="width: 185px"
          placeholder="申请人"
          class="filter-item"
          :remote-method="getName"
          @keyup.enter.native="crud.toQuery"
        >
          <el-option
            v-for="item in nameList"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
        <label class="el-form-item-label">订单号</label>
        <el-input
          v-model="query.no"
          clearable
          placeholder="订单号"
          style="width: 185px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <label class="el-form-item-label">时间</label>
        <date-range-picker v-model="query.createdAt" class="date-item" />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="500px"
      >
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          size="small"
          label-width="80px"
        />
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button
            :loading="crud.status.cu === 2"
            type="primary"
            @click="crud.submitCU"
            >确认</el-button
          >
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="userName" label="申请人" />
        <el-table-column label="明细">
          <template slot-scope="scope">
            {{ getReagent(scope.row.store) }}
          </template>
        </el-table-column>
        <el-table-column prop="no" label="订单号" />
        <el-table-column prop="createdAt" label="时间" />
        <el-table-column prop="note" label="申请人备注" />
        <el-table-column fixed="right" width="150px" label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="applySendBack(scope.row)"
              >详情</el-button
            >
          </template>
        </el-table-column>
        <!-- <el-table-column v-if="checkPer(['admin','sensorLog:edit','sensorLog:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column> -->
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
    <el-dialog
      :close-on-click-modal="false"
      title="详情"
      :visible.sync="showReback"
      width="60%"
    >
      <el-form ref="rebackForm" :model="formData">
        <el-table
          :header-cell-style="{ background: '#fafafa' }"
          :data="formData.rebackList"
          style="width: 100%"
        >
          <el-table-column
            width="100px"
            type="index"
            label="序号"
            align="center"
          />
          <el-table-column prop="name" label="名称" align="center" />
          <el-table-column prop="number" label="1单位容量" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.number }}{{ scope.row.unit }}</span>
            </template>
          </el-table-column>
          <el-table-column label="实际归还量" align="center">
            <template slot-scope="scope">
              <el-form-item
                :prop="'rebackList.' + scope.$index + '.backAmount'"
                :rules="rules.backAmount"
              >
                <el-input-number
                  size="small"
                  :max="scope.row.number"
                  v-model="scope.row.backAmount"
                  :min="0"
                  :precision="1"
                ></el-input-number>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="条码" align="center">
            <template slot-scope="scope">
              <el-form-item
                :prop="'rebackList.' + scope.$index + '.barCode'"
                :rules="rules.barCode"
              >
                <el-input size="small" v-model="scope.row.barCode"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doApplySendBack('rebackForm')"
          >归 还
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import crudHazardousChemicals from "@/api/hazardousChemicals";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import rrOperation from "@crud/RR.operation";
import crudOperation from "@crud/CRUD.operation";
import udOperation from "@crud/UD.operation";
import pagination from "@crud/Pagination";
import { rebackList, returnHazardousChemicals } from "@/api/hazardousChemicals";
import { get, findAdmin } from "@/api/lab";
import DateRangePicker from "@/components/DateRangePicker";
import { allNamelist } from "@/api/user";

const defaultForm = {
  id: null,
  name: null,
  type: 2,
  amount: null,
  labId: null,
  note: null,
  createdAt: null,
  isDeleted: null,
  countType: null,
  updatedAt: null,
  barCode: null,
  cabinetId: null,
  measureId: 1,
  dangerClasses: null,
};
export default {
  name: "Audit",
  components: {
    pagination,
    crudOperation,
    rrOperation,
    udOperation,
    DateRangePicker,
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({
      title: "申领审核列表",
      url: "api/storehouseOrder/returnList",
      idField: "id",
      sort: "id,desc",
      crudMethod: { ...crudHazardousChemicals },
      optShow: {
        add: false,
        edit: false,
        del: false,
        download: true,
        reset: true,
      },
    });
  },
  data() {
    return {
      reason: "",
      permission: {
        add: ["admin", "sensorLog:add"],
        edit: ["admin", "sensorLog:edit"],
        del: ["admin", "sensorLog:del"],
      },
      rules: {
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        // type: [
        //   { required: true, message: '危化品类型不能为空', trigger: 'blur' }
        // ],
        // amount: [{ required: true, message: "数量不能为空", trigger: "blur" }],
        labId: [
          { required: true, message: "实验室不能为空", trigger: "change" },
        ],
        barCode: [{ required: true, message: "条码不能为空", trigger: "blur" }],
        cabinetId: [
          { required: true, message: "试剂柜不能为空", trigger: "change" },
        ],
        // measureId: [
        //   { required: true, message: '计量方式不能为空', trigger: 'blur' }
        // ],
        backAmount: [
          {
            required: true,
            message: "实际归还数量不能为空",
            trigger: "blur",
          },
        ],
      },
      queryTypeOptions: [
        { key: "name", display_name: "名称" },
        // { key: 'type', display_name: '危化品类型' },
        { key: "labName", display_name: "实验室" },
        { key: "countType", display_name: "计数类型" },
        { key: "cabinetName", display_name: "试剂柜" },
        // { key: 'measureId', display_name: '计量方式' },
        { key: "dangerClasses", display_name: "危险等级" },
      ],
      admins: [],
      nameList: [],
      formData: {
        rebackList: [],
      },
      showReback: false,
      id: null,
    };
  },
  created() {
    this.getAdmins();
    this.getName();
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true;
    },
    dateFormat(picker) {
      if (picker == null) {
        this.form.createdAt = null;
        this.form.updatedAt = null;
      } else {
        this.form.createdAt = picker[0];
        this.form.updatedAt = picker[1];
      }
    },
    getName() {
      allNamelist()
        .then((response) => {
          this.nameList = response.content;
          console.log(this.nameList);
        })
        .catch((_) => {
          // console.log(response);
        });
    },
    getAdmins() {
      findAdmin()
        .then((response) => {
          this.admins = response;
        })
        .catch((_) => {
          console.log(response);
        });
    },
    getReagent(data) {
      var text = "";
      data.forEach((item) => {
        text += item.name + "×" + item.num + item.unit + "、";
      });
      return text ? text.substring(0, text.length - 1) : "-";
    },
    applySendBack(data) {
      this.crud.refresh(); //刷新页面
      this.formData.rebackList = [];
      this.id = data.id;
      this.showReback = true;
      this.formData.rebackList = data.detailList;
      rebackList();
    },
    doApplySendBack(form) {
      const arr = this.formData.rebackList.map((item) => {
        return { barCode: item.barCode, backAmount: item.backAmount };
      });
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.$confirm("确定要归还该订单吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              returnHazardousChemicals({
                id: this.id,
                data: JSON.stringify(arr),
              }).then(() => {
                this.showReback = false;
                this.formData.rebackList = [];
                this.crud.refresh();
              });
            })
            .catch(() => {
              //取消
            });
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style scoped></style>
